<template>
  <view class="warehouse-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">红冲作业</text>
    </view>

    <!-- 红冲信息区域 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">红冲信息</text>
      </view>

      <!-- 红冲类型标签页 -->
      <!-- <view class="in-type-tabs">
        <view
          class="tab-item"
          :class="{ active: currentInType === 'weigh' }"
          @click="switchInType('weigh')"
        >
          <text class="tab-text">缴库</text>
        </view>
      </view> -->

      <view class="info-form">
        <view class="form-item">
          <text class="form-label">红冲日期</text>
          <picker
            class="form-picker"
            mode="date"
            :value="formData.inDate"
            @change="handleDateChange"
          >
            <view class="picker-content">
              <text>{{ formData.inDate }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">目标仓库</text>
          <view class="warehouse-display">{{
            currentWarehouse ? currentWarehouse.warehouseName : "请选择"
          }}</view>
        </view>
      </view>
    </view>

    <!-- 待红冲区域 -->
    <view class="search-section">
      <view class="search-form">
        <view class="section-header">
          <text class="section-title">待红冲</text>
          <input
            ref="materialInput"
            v-model="searchForm.searchCode"
            class="material-input"
            placeholder="请输入箱号/轴号"
            @confirm="searchPackPrintRecords"
            @focus="handleInputFocus"
            @blur="handleInputBlur"
            :focus="inputFocus"
          />
          <button class="scan-btn" @click="searchPackPrintRecords">查询</button>
        </view>
      </view>
    </view>

    <!-- 待红冲表格 -->
    <view v-if="packPrintRecords.length > 0" class="material-table-section">
      <view class="table-body">
        <view class="table-row header">
          <view class="table-cell">选择</view>
          <view class="table-cell">箱号</view>
          <!-- <view class="table-cell">轴号</view> -->
          <view class="table-cell">钢种</view>
          <view class="table-cell">规格</view>
          <view class="table-cell">净重(KG)</view>
        </view>
        <view
          v-for="(item, index) in packPrintRecords"
          :key="index"
          class="table-row"
          :class="{
            selected: isRecordSelected(item),
          }"
          @click="toggleRecordSelection(item, index)"
        >
          <view class="table-cell">
            <text v-if="isRecordSelected(item)" class="check-icon">✓</text>
            <text v-else class="uncheck-icon">○</text>
          </view>
          <view class="table-cell">{{ item.boxCode || "-" }}</view>
          <!-- <view class="table-cell">{{ item.axisCode || "-" }}</view> -->
          <!-- <view class="table-cell">{{ item.customerName || "-" }}</view> -->
          <view class="table-cell">{{ item.steelGrade || "-" }}</view>
          <view class="table-cell">{{ item.spec || "-" }}</view>
          <view class="table-cell">{{ item.weightOfNet || 0 }}</view>
        </view>
      </view>
    </view>
    <!-- 统计信息 -->
    <view class="material-table-section">
      <view class="statistics-section">
        <view class="stat-item">
          <text class="stat-label">选中记录数</text>
          <text class="stat-value">{{ selectedRecords.length }}</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">总重量</text>
          <text class="stat-value">{{ totalWeight }} KG</text>
        </view>
      </view>
      <!-- 底部操作栏 -->
      <view class="action-bar">
        <view class="action-row">
          <button class="btn-reset" @click="resetForm">重置</button>
          <button class="btn-submit" @click="submitForm">提交红冲</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { ProdStockInApi } from "@/api/warehouse/prodstockin";
export default {
  name: "InWarehouseCreate",
  data() {
    return {
      // 入库类型配置
      inTypeOptions: [{ value: "manual", label: "在制品入库" }],
      inTypeIndex: 0,

      // 表单数据
      formData: {
        inType: "weigh",
        inDate: this.getCurrentDate(),
        warehouseId: "",
        warehouseName: "",
      },

      // 搜索表单
      searchForm: {
        searchCode: "",
      },

      // 数据列表
      currentWarehouse: null,

      // 包装打印记录数据
      packPrintRecords: [
        {
          id: 1,
          boxCode: "BOX2025001",
          axisCode: "AXIS001",
          steelGrade: "Q245",
          spec: "φ16",
          weightOfNet: 1250.5,
        },
        {
          id: 2,
          boxCode: "BOX2025002",
          axisCode: "AXIS002",
          steelGrade: "Q245",
          spec: "φ16",
          weightOfNet: 1380.25,
        },
      ], // 包装打印记录列表
      selectedRecords: [], // 选中的记录列表（支持多选）

      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        startDate: "", // 开始日期
        endDate: "", // 结束日期
      },

      // 输入框聚焦状态
      inputFocus: true,
    };
  },

  computed: {
    currentInType() {
      return this.inTypeOptions[this.inTypeIndex]?.value;
    },

    totalWeight() {
      // 根据选中的记录计算总重量
      return this.selectedRecords.reduce(
        (sum, item) => sum + (Number(item.weightOfNet) || 0),
        0
      );
    },
  },

  mounted() {
    this.loadInitialData();
    // 页面加载完成后聚焦到输入框
    this.$nextTick(() => {
      this.focusInput();
    });
  },

  watch: {
    contractTable: {
      handler(newVal, oldVal) {
        console.log("contractTable发生变化:", {
          oldLength: oldVal ? oldVal.length : 0,
          newLength: newVal ? newVal.length : 0,
          newData: newVal,
        });
      },
      deep: true,
    },
    showContractTable: {
      handler(newVal, oldVal) {
        console.log("showContractTable发生变化:", {
          oldValue: oldVal,
          newValue: newVal,
        });
      },
    },
  },

  methods: {
    // 格式化日期（处理时间戳）
    formatDate(timestamp) {
      if (!timestamp) return "-";
      try {
        // 如果是时间戳（毫秒）
        if (typeof timestamp === "number" && timestamp > 1000000000000) {
          const date = new Date(timestamp);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, "0");
          const day = String(date.getDate()).padStart(2, "0");
          const hours = String(date.getHours()).padStart(2, "0");
          const minutes = String(date.getMinutes()).padStart(2, "0");
          return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        // 如果已经是字符串格式
        return timestamp;
      } catch (error) {
        console.error("日期格式化错误:", error);
        return timestamp;
      }
    },

    // 格式化日期时间（包含秒）
    formatDateTime(timestamp) {
      if (!timestamp) return "-";
      try {
        // 如果是时间戳（毫秒）
        if (typeof timestamp === "number" && timestamp > 1000000000000) {
          const date = new Date(timestamp);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, "0");
          const day = String(date.getDate()).padStart(2, "0");
          const hours = String(date.getHours()).padStart(2, "0");
          const minutes = String(date.getMinutes()).padStart(2, "0");
          const seconds = String(date.getSeconds()).padStart(2, "0");
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
        // 如果已经是字符串格式，尝试解析
        if (typeof timestamp === "string") {
          const date = new Date(timestamp);
          if (!isNaN(date.getTime())) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
          }
        }
        return timestamp;
      } catch (error) {
        console.error("日期时间格式化错误:", error);
        return timestamp;
      }
    },

    // 获取当前日期
    getCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    // 加载初始数据
    async loadInitialData() {
      try {
        // 加载当前用户仓库
        const warehouseRes = await this.getCurrentWarehouse();
        if (warehouseRes) {
          this.currentWarehouse = warehouseRes;
          this.formData.warehouseId = warehouseRes.warehouseId;
          this.formData.warehouseName = warehouseRes.warehouseName;
        }
      } catch (error) {
        console.error("加载初始数据失败:", error);
      }
    },

    // 获取当前用户仓库
    async getCurrentWarehouse() {
      try {
        // 从Vuex store获取用户配置的仓库信息
        const userConfig = this.$store.state.user.userConfig;
        if (userConfig && userConfig.wmName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.wmName,
          };
        }

        // 降级处理：尝试其他字段
        if (userConfig && userConfig.warehouseName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.warehouseName,
          };
        }
      } catch (error) {
        console.error("获取用户仓库失败:", error);
      }

      // 默认值
      return {
        warehouseId: "DEFAULT",
        warehouseName: "默认仓库",
      };
    },

    // 切换入库类型（标签页方式）
    switchInType(type) {
      // 检查是否有未红冲的数据
      if (this.materialList.length > 0) {
        uni.showModal({
          title: "提示",
          content: "有数据未红冲，请先提交红冲或删除待红冲数据",
          confirmText: "去提交",
          cancelText: "删除数据",
          success: (res) => {
            if (res.confirm) {
              // 用户选择去提交，不做任何操作
              return;
            } else if (res.cancel) {
              // 用户选择删除数据，清空materialList
              this.materialList = [];
              // 同时清除原表格中的选中状态
              this.clearOriginalTableSelection();
              // 继续切换入库类型
              this.continueInTypeChange(type);
            }
          },
        });
      } else {
        // 没有数据，直接切换
        this.continueInTypeChange(type);
      }
    },

    // 继续入库类型变更
    continueInTypeChange(type) {
      // 根据类型设置对应的索引
      const typeIndex = this.inTypeOptions.findIndex(
        (item) => item.value === type
      );
      if (typeIndex !== -1) {
        this.inTypeIndex = typeIndex;
        this.formData.inType = type;
      }

      // 重置搜索条件
      this.resetSearch();

      // 重置所有查询结果表
      this.resetQueryResults();
    },

    // 清除原表格中的选中状态
    clearOriginalTableSelection() {
      this.materialTable.forEach((item) => {
        if (item.isCheck) {
          this.$set(item, "isCheck", false);
          this.$set(item, "showError", false);
          this.$set(item, "prod_count", 0);
          this.$set(item, "trans_count", 0);
        }
      });
    },

    // 处理返回按钮点击
    handleBack() {
      // 检查是否有未红冲的数据
      if (this.materialList.length > 0) {
        uni.showModal({
          title: "提示",
          content: "有数据未红冲，请先提交红冲或删除待红冲数据",
          confirmText: "去提交",
          cancelText: "删除数据",
          success: (res) => {
            if (res.confirm) {
              // 用户选择去提交，不做任何操作
              return;
            } else if (res.cancel) {
              // 用户选择删除数据，清空materialList
              this.materialList = [];
              // 同时清除原表格中的选中状态
              this.clearOriginalTableSelection();
              // 返回上一页
              uni.navigateBack();
            }
          },
        });
      } else {
        // 没有数据，直接返回
        uni.navigateBack();
      }
    },

    // 重置所有查询结果表
    resetQueryResults() {
      // 重置合同表
      this.contractTable = [];
      this.showContractTable = false;

      // 重置检斤表
      this.weightTable = [];
      this.showWeightTable = false;
      this.selectedWeightRow = null;

      // 重置物料表
      this.materialTable = [];

      // 重置物料编码和名称输入
      this.materialCode = "";
      this.materialName = "";

      // 重置时间筛选
      this.timeFilter = "today";
    },

    // 日期变更
    handleDateChange(e) {
      // 获取选择的日期
      const selectedDate = e.detail.value;
      // 获取当前时间，保持时分秒
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      // 组合成完整的日期时间格式
      this.formData.inDate = `${selectedDate} ${hours}:${minutes}:${seconds}`;
    },

    // 供应商变更
    handleSupplierChange(e) {
      this.supplierIndex = e.detail.value;
      const selectedSupplier = this.supplierList[this.supplierIndex];
      if (selectedSupplier) {
        this.searchForm.supplierId = selectedSupplier.supplierId;
        this.searchForm.supplierName = selectedSupplier.supplierName;
      }
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        searchCode: "",
      };
      this.packPrintRecords = [];
      this.selectedRecords = [];
    },

    // 输入框聚焦处理
    handleInputFocus() {
      // 隐藏输入法（uniapp环境）
      if (uni.hideKeyboard) {
        uni.hideKeyboard();
      }
      this.inputFocus = true;
    },

    // 输入框失焦处理
    handleInputBlur() {
      // 延迟重新聚焦，避免快速失焦导致的闪烁
      setTimeout(() => {
        this.focusInput();
      }, 100);
    },

    // 聚焦到输入框
    focusInput() {
      this.inputFocus = true;
      // 使用nextTick确保DOM更新完成
      this.$nextTick(() => {
        if (this.$refs.materialInput) {
          // 尝试多种聚焦方式以确保兼容性
          try {
            this.$refs.materialInput.focus();
          } catch (e) {
            console.log("聚焦失败，尝试备用方案");
          }
        }
      });
    },

    // 搜索红冲记录
    async searchPackPrintRecords() {
      try {
        uni.showLoading({ title: "查询中..." });

        // 红冲作业查询参数：pagesize,no,1,100,boxCode,axisCode
        const params = {
          page: 1,
          pageSize: 100,
          boxCode: this.searchForm.searchCode || undefined,
          axisCode: this.searchForm.searchCode || undefined,
        };

        const res = await ProdStockInApi.getProdStockInPage(params);

        if (res.code === 0) {
          this.packPrintRecords = res.data?.list || [];
          // 依据返回的productType 判断 细丝按照箱号汇总，其他按照轴号汇总给packPrintRecords
          if (this.currentWarehouse?.warehouseName === "细丝") {
            this.packPrintRecords = this.packPrintRecords.reduce((acc, cur) => {
              const existing = acc.find(
                (item) => item.box_code === cur.box_code
              );
              if (existing) {
                existing.weightOfNet += cur.weightOfNet;
              } else {
                acc.push({ ...cur });
              }
              return acc;
            }, []);
          } else {
            this.packPrintRecords = this.packPrintRecords.reduce((acc, cur) => {
              const existing = acc.find(
                (item) => item.axis_code === cur.axis_code
              );
              if (existing) {
                existing.weightOfNet += cur.weightOfNet;
              } else {
                acc.push({ ...cur });
              }
              return acc;
            }, []);
          }

          // 保留之前已选中的记录，同时选中新查询的记录
          if (this.packPrintRecords.length > 0) {
            // 合并之前选中的记录和新查询的记录，避免重复
            const allSelectedRecords = [...this.selectedRecords];
            this.packPrintRecords.forEach(newRecord => {
              if (!allSelectedRecords.some(item => item.id === newRecord.id)) {
                allSelectedRecords.push(newRecord);
              }
            });
            this.selectedRecords = allSelectedRecords;
          }

          // 查询完成后清空输入框，便于下次输入
          this.searchForm.searchCode = "";

          // 重新聚焦到输入框
          this.$nextTick(() => {
            this.focusInput();
          });

          uni.showToast({
            title: `查询到${this.packPrintRecords.length}条记录，已自动选中`,
            icon: "success",
          });
        }
      } catch (error) {
        console.error("查询包装打印记录失败:", error);
        uni.showToast({ title: "查询失败，请重试", icon: "none" });
      } finally {
        uni.hideLoading();
      }
    },

    // 判断记录是否被选中
    isRecordSelected(record) {
      return this.selectedRecords.some((item) => item.id === record.id);
    },

    // 切换记录选中状态
    toggleRecordSelection(record, index) {
      const existingIndex = this.selectedRecords.findIndex(
        (item) => item.id === record.id
      );

      if (existingIndex !== -1) {
        // 如果已选中，则取消选中
        this.selectedRecords.splice(existingIndex, 1);
      } else {
        // 否则添加到选中列表
        this.selectedRecords.push({ ...record });
      }
    },

    // 重置表单
    resetForm() {
      this.formData.inDate = this.getCurrentDate();
      this.resetSearch();
    },

    // 提交表单
    async submitForm() {
      console.log("【提交表单】", this.formData);
      // 显示加载状态
      uni.showLoading({
        title: "正在提交...",
        mask: true,
      });

      try {
        // 验证：必填字段检查
        const validation = this.validateForm();
        if (!validation.valid) {
          uni.hideLoading();
          uni.showToast({
            title: validation.message,
            icon: "none",
            duration: 2000,
          });
          return;
        }

        // 提交前确认
        const confirmRes = await this.showSubmitConfirm();
        if (!confirmRes) {
          uni.hideLoading();
          return;
        }

        // 构建红冲数据
        const submitData = {
          boxList: this.selectedRecords.map((record) => record.boxCode),
          axisList: this.selectedRecords.map((record) => record.axisCode),
        };

        console.log("提交红冲数据:", submitData);

        // 调用红冲API - 批量删除入库记录
        const response = await ProdStockInApi.deleteProdStockIn(submitData);

        // 隐藏加载状态
        uni.hideLoading();

        if (response.key === "") {
          // 处理成功
          await this.handleSubmitSuccess(response);
        } else {
          // 处理失败
          await this.handleSubmitException({
            message: response.msg || "提交红冲失败",
          });
        }
      } catch (error) {
        console.error("提交红冲失败:", error);

        // 隐藏加载状态
        uni.hideLoading();

        // 处理异常
        await this.handleSubmitException(error);
      }
    },

    // 表单验证
    validateForm() {
      if (!this.formData.warehouseName) {
        return { valid: false, message: "请选择仓库" };
      }

      if (!this.formData.inDate) {
        return { valid: false, message: "请选择入库日期" };
      }

      if (this.selectedRecords.length === 0) {
        return { valid: false, message: "请选择要红冲的记录" };
      }

      return { valid: true };
    },

    // 验证数字有效性
    isValidNumber(value) {
      return (
        value !== null &&
        value !== undefined &&
        !isNaN(value) &&
        isFinite(value)
      );
    },

    // 显示提交确认
    showSubmitConfirm() {
      return new Promise((resolve) => {
        const recordCount = this.selectedRecords.length;
        const totalWeight = this.totalWeight;

        uni.showModal({
          title: "确认提交",
          content: `共${recordCount}条记录，总重量：${totalWeight}KG，是否确认提交红冲？`,
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            resolve(res.confirm);
          },
        });
      });
    },

    // 处理提交成功
    async handleSubmitSuccess(res) {
      uni.showToast({
        title: "入库单创建成功",
        icon: "success",
        duration: 2000,
      });

      // 记录成功日志
      console.log("入库单创建成功:", res.data);

      // 重置表单
      this.resetForm();

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 2000);
    },

    // 处理提交异常
    async handleSubmitException(error) {
      console.error("提交表单异常:", error);

      let errorMsg = "提交失败，请重试";

      // 网络错误处理
      if (error.message && error.message.includes("Network")) {
        errorMsg = "网络连接失败，请检查网络后重试";
      } else if (error.code === "ECONNABORTED") {
        errorMsg = "请求超时，请稍后重试";
      } else if (error.response && error.response.status) {
        switch (error.response.status) {
          case 400:
            errorMsg = "请求参数错误，请检查输入数据";
            break;
          case 401:
            errorMsg = "登录已过期，请重新登录";
            break;
          case 403:
            errorMsg = "没有权限执行此操作";
            break;
          case 500:
            errorMsg = "服务器错误，请稍后重试";
            break;
          default:
            errorMsg = `服务器错误 (${error.response.status})，请稍后重试`;
        }
      }

      uni.showModal({
        title: "提交失败",
        content: errorMsg,
        showCancel: false,
        confirmText: "知道了",
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "~@/pages/smart/scss/create.scss";
</style>
